<template>
    <div class="qr-box" v-loading="pageLoading">
        <div style="width: 100%;">
            <div class="file-row">
                <v-file-input class="file-path" label="选择文件" prepend-icon="mdi-file" show-size v-model="filePath"
                    variant="outlined" @update:modelValue="handleFileSelected" :multiple="true"></v-file-input>
                <div class="file-btn"><v-text-field label="分片大小(Bytes)" type="number"
                        v-model="sliceSize"></v-text-field></div>
                <div class="file-btn"><v-btn block @click="generateQrCode" :min-height="55">生成二维码</v-btn></div>
            </div>
            <v-divider style="margin: 10px 0px;"></v-divider>
            <v-alert v-model="alertMsg" border="start" title="转换二维码" variant="tonal" closable
                color="deep-purple-accent-4">{{ errorMsg }}</v-alert>
        </div>
        <v-img class="qr-image" v-if="qrImages.length > 0" :src="qrImages[qrImageIdx]"></v-img>
        <v-pagination v-if="qrImages.length > 0" :length="qrImages.length" :showFirstLastPage="true" v-model="qrPageIdx"
            :update:modelValue="changeQrPage"></v-pagination>
    </div>
</template>
<script>
import { Buffer } from 'buffer';
import { CRC32 } from '@/utils/crc';

export default {
    data: () => ({
        filePath: null,
        originFile: null,
        alertMsg: false,
        errorMsg: "",
        qrImages: [],
        qrImageIdx: 0,
        qrPageIdx: 1,
        sliceSize: 2000,
        pageLoading: false,
    }),
    methods: {
        generateQrCode() {
            if (this.originFile == null) {
                this.qrImages = [];
                this.errorMsg = "请先输入二维码的文本内容";
                this.alertMsg = true;
                return;
            }
            this.pageLoading = true;
            this.alertMsg = false;
            const QRCode = require('qrcode');
            // options for qrcode
            const qrOptions = {
                errorCorrectionLevel: 'L',
                type: 'image/png',
                quality: 1,
                margin: 1,
            };
            try {
                // read file
                let reader = new FileReader();
                reader.onload = async (e) => {
                    try {
                        // 总数|页码|分页CRC[|文件CRC|文件名]|内容，
                        let content = Buffer.from(e.target.result);
                        const sliceSize = Number(this.sliceSize);
                        const totalPage = Math.ceil(content.byteLength / sliceSize);
                        const fileName = this.originFile.name;
                        const crc = new CRC32();
                        crc.update(content);
                        const totalCrc = crc.getResult();
                        this.qrImages = [];
                        for (let i = 0, curPage = 0; i < content.byteLength; i += sliceSize, curPage++) {
                            // content
                            try {
                                const sliceData = content.subarray(i, i + sliceSize);
                                console.log(sliceData);
                                crc.reset();
                                crc.update(sliceData);
                                const sliceCrc = crc.getResult();
                                const sliceContent = sliceData.toString('base64');
                                const sliceText = 'A' + totalPage.toString(16) + "|" + curPage.toString(16) + "|"
                                    + sliceCrc + "|" + totalCrc + "|" + fileName + "|" + sliceContent;
                                const data = await QRCode.toDataURL(sliceText, qrOptions);
                                this.qrImages.push(data);
                            } catch (err) {
                                this.errorMsg = "编码分片[" + (curPage + 1).toString() + "]出错：" + String(err);
                                this.alertMsg = true;
                            }
                        }
                        this.qrPageIdx = 1;
                    } catch (err) {
                        this.errorMsg = "编码文件出错：" + String(err);
                        this.alertMsg = true;
                    } finally {
                        this.pageLoading = false;
                    }
                };
                reader.readAsArrayBuffer(this.originFile);
            } catch (err) {
                this.errorMsg = "读取文件出错：" + String(err);
                this.alertMsg = true;
                this.pageLoading = false;
            }
        },
        changeQrPage(e) {
            console.log(e);
        },
        handleFileSelected(event) {
            if (event === undefined || event === null) {
                this.originFile = null;
            } else if (Array.isArray(event)) {
                // [object Array]
                this.originFile = event.length > 0 ? event[0] : null;
            } else {
                // [object File]
                this.originFile = event;
            }
        }
    },
    watch: {
        qrPageIdx: function (newVal, oldVal) {
            this.qrImageIdx = newVal - 1;
        }
    }
}
</script>
<style scoped>
.qr-box {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.file-row {
    display: flex;
    flex-direction: row;
    width: 100%;
}

.file-path {
    flex: 1;
}

.file-btn {
    width: 160px;
    padding: 0 10px;
}

.qr-image {
    flex: 1;
}
</style>
